package com.anosine.gpsl.android.util;

import java.io.File;

import com.anosine.gpsl.android.AppConstants;
import com.anosine.gpsl.android.R;
import com.anosine.gpsl.android.entity.UpdataInfoBean;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.format.Formatter;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
 * 文件名：ShowDownloadProgressDlgA 功能：下载更新提示框 作者：sunny 日期：2015.10.29 版权：公司
 * */
public class ShowDownloadProgressDlgA {

	private static UpdataInfoBean mInfo;
	private final static String mSaveApkName = "lovecar.apk";
	private Context context;
	private static Dialog dlg;

	/**
	 * 方法名：ShowDownloadProgressDlgA(Context context, UpdataInfoBean info) 功能：初始化
	 * 参数：Context context 上下文, UpdataInfoBean info 更新bean
	 * */
	public ShowDownloadProgressDlgA(Context context, UpdataInfoBean info) {
		dlg = new Dialog(context, R.style.custom_dlg);
		this.context = context;
		mInfo = info;
		LayoutInflater layout = LayoutInflater.from(context);
		View view = layout
				.inflate(R.layout.dlg_show_download_progressbar, null);
		mPbShow = (ProgressBar) view.findViewById(R.id.pb_dlg_update_show);
		mTvShowInfo = (TextView) view.findViewById(R.id.tv_dlg_update_show);
		mTvUpdateInfo = (TextView) view.findViewById(R.id.tv_dlg_update_info);
		if (mInfo != null) {
			mTvUpdateInfo.setText(mInfo.getDescription());
		}
		dlg.setContentView(view);
		dlg.setCanceledOnTouchOutside(false);
		WindowManager.LayoutParams layoutParams = dlg.getWindow()
				.getAttributes();
		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		int mScreenWidth = wm.getDefaultDisplay().getWidth();
		layoutParams.width = (int) (mScreenWidth * 0.9f);
		beginDownload(context);
		dlg.show();
	}

	/**
	 * 文件名：dismiss() 功能：提示框消失 参数：无
	 * 
	 * @return none
	 * */
	public void dismiss() {
		if (dlg != null)
			dlg.dismiss();
	}

	/**
	 * 文件名：getCancel() 功能：获取提示框 中的取消下载按钮 参数：无
	 * 
	 * @return TextView
	 * */
	public TextView getCancel() {
		return ((TextView) dlg.findViewById(R.id.btn_confirm_dlg_cancel));
	}

	private static TextView mTvShowInfo;
	private static TextView mTvUpdateInfo;

	private static ProgressBar mPbShow;
	private static HttpHandler handler;

	/**
	 * 文件名：beginDownload(final Context context) 功能：开始下载apk 参数：Context context
	 * 上下文
	 * 
	 * @return 无
	 * */
	private static void beginDownload(final Context context) {
		File f = new File(AppConstants.PATH_APK);
		if (!f.exists()) {
			f.mkdirs();
		}
		String savePath = AppConstants.PATH_APK + mSaveApkName;

		RequestCallBack<File> response = new RequestCallBack<File>() {
			/**
			 * 文件名：onLoading(long total, long current, boolean isUploading)
			 * 功能：通过RequestCallBack这个类来回调处理返回的数据 ，并书写回调函数 ，使用xutils更新ProgressBar
			 * 参数：long total 总长度, long current 现在的长度, boolean isUploading 是否上传
			 * 返回值：无*/
			@Override
			public void onLoading(long total, long current, boolean isUploading) {
				if (context != null) {
					String speed = String.format("%1s/%2s",
							Formatter.formatFileSize(context, current),
							Formatter.formatFileSize(context, total));
					mTvShowInfo.setText(speed);
					int progress = 0;
					if (total != 0) {
						progress = (int) (1.0f * current / total * 100);
					}
					mPbShow.setProgress(progress);
				}
			}
			/**
			 * 方法名：onSuccess(ResponseInfo<File> responseInfo)
			 * 功能：回调成功
			 * 参数：ResponseInfo<File> responseInfo 返回值
			 * @return none*/
			@Override
			public void onSuccess(ResponseInfo<File> responseInfo) {
				try {
					String filePath = responseInfo.result.getPath();
					File file = new File(filePath);
					if (file.exists() && file.isFile()) {
						installApk(file, context);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
			/**
			 * 方法名：onFailure(HttpException error, String msg)
			 * 功能：回调失败
			 * 参数：HttpException error 抛异常, String msg 错误信息
			 * @return none*/
			@Override
			public void onFailure(HttpException error, String msg) {
				ToastHelper.toast(msg);
			}
		};

		response.setRate(200);
		HttpUtils http = new HttpUtils();
		handler = http.download(mInfo.getUrl(), savePath, false, false,
				response);

	}

	/**
	 * 方法名：installApk(File file, Context context) 功能：下载安装apk 参数：File file 下载路径,
	 * Context context 上下文
	 * 
	 * @return none
	 */
	protected static void installApk(File file, Context context) {
		if (context != null) {
			Intent intent = new Intent();
			intent.setAction(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.fromFile(file),
					"application/vnd.android.package-archive");
			context.startActivity(intent);
			dlg.dismiss();
		}
	}

	// private void dismissSetInfoNull() {
	// if (handler != null && !handler.isCancelled()) {
	// handler.cancel();
	// }
	// }

}
